package com.nw.interceptor;

import com.nw.utils.StringUtil;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Enumeration;

public class InterceptorConfig  implements HandlerInterceptor{

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(InterceptorConfig.class);

    /**
     * 进入controller层之前拦截请求
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("---------获取请求头方式1-------------");
        // 拿到指定的请求头
        System.out.println(httpServletRequest.getHeader("cache-control"));

        System.out.println("---------获取请求头方式2-------------");
        // 拿到所有指定的请求头
        Enumeration e = httpServletRequest.getHeaders("cache-control");
        while (e.hasMoreElements()) {
            String headValue = (String) e.nextElement();
            System.out.println(headValue);
        }

        System.out.println("---------获取请求头方式3-------------");
        // 拿到所有请求头
        Enumeration e1 = httpServletRequest.getHeaderNames();
        while (e1.hasMoreElements()) {
            String headerName = (String) e1.nextElement();
            String headValue = httpServletRequest.getHeader(headerName);
            System.out.println(headerName + "=" + headValue);
        }
        log.info("---------------------开始进入请求地址拦截----------------------------");
        HttpSession session = httpServletRequest.getSession();
        if(!StringUtil.isEmpty(session.getAttribute("userName"))){
            return true;
        }
        else{
            PrintWriter printWriter = httpServletResponse.getWriter();
            printWriter.write("{code:0,message:\"session is invalid,please login again!\"}");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("---------------视图渲染之后的操作-------------------------0");
    }
}